package stack.字符串解码;

import java.util.Collections;
import java.util.LinkedList;

public class Solution {
    public String decodeString(String s) {
        LinkedList<String> list = new LinkedList<>();
        int index = 0;
        while (index < s.length()) {
            char c = s.charAt(index);
            //数字进栈
            if (Character.isDigit(c)) {
                //如果数字是多位数需要额外处理
                int tIndex = index + 1 ;
                while (Character.isDigit(s.charAt(tIndex))) {
                    tIndex++;
                }
                list.addLast(s.substring(index, tIndex));
                index = tIndex ;
            }
            //字母或者]进栈
            else if (Character.isLetter(c) || c == '[') {
                index++;
                list.addLast(String.valueOf(c));
            }
            //遇到结束标志 ] ， 处理字符串
            else {
                index++;
                LinkedList<String> l = new LinkedList();
                while (!"[".equals(list.peekLast())) {
                    l.addLast(list.removeLast());
                }
                list.removeLast();
                //处理字符串
                StringBuffer buffer =new StringBuffer();
                while (!l.isEmpty()){
                    buffer.append(l.removeLast());
                }
                //处理循环
                int k = Integer.valueOf(list.removeLast());
                StringBuffer temp = new StringBuffer();
                while (k-- > 0) {
                    temp.append(buffer);
                }
                list.addLast(temp.toString());
            }

        }
        return getString(list);
    }

    String getString(LinkedList<String> list) {
        StringBuffer s = new StringBuffer();
        while (!list.isEmpty()) {
            s.append(list.removeFirst());
        }
        return s.toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.decodeString("3[z]2[2[y]pq4[2[jk]e1[f]]]ef"));
    }
/**
 * zzzyypqfejkjkfejkjkfejkjkfejkjkyypqfejkjkfejkjkfejkjkfejkjkef
 * zzzyypqjkjkefjkjkefjkjkefjkjkefyypqjkjkefjkjkefjkjkefjkjkefef
 * zzzyypqjkjkefjkjkefjkjkefjkjkefyypqjkjkefjkjkefjkjkefjkjkefef
 *
 *
 */
}
